import React, { FC, memo, ReactNode, useEffect, useState } from 'react'
import { Button, FormInstance, Input, Rate, Space, Tag, theme } from 'antd'
import ReactHighlightSyntax from 'react-highlight-syntax'
import PageSearch from '@/components/page-search'
import PageContent from '@/components/page-content'
import PageModal from '@/components/page-modal'
import VerifyCodeButton from '@/components/verify-code-button'
import usePageSearch from '@/hooks/use-page-search'
import usePageContent from '@/hooks/use-page-content'
import usePageModal from '@/hooks/use-page-modal'
import {
  fetchPageBatchDeleteAction,
  fetchPageDeleteAction
} from '@/store/module/main/page-common'
import { getClassifyTypeQuestion } from '@/service/module/main/classify/question'
import confirmModal from '@/utils/confirm-modal'
import { localCache } from '@/utils/cache'
import { ActionDesc, CacheType, RoutesPath, ThemeMode } from '@/global/constant'
import getQuestionListSearch from './config/question-list-search'
import questionListContent from './config/question-list-content'
import questionListModalDetail from './config/question-list-modal-detail'
import { CateTypeWrapper, DetailWrapper } from './style'
import { useNavigate } from 'react-router-dom'

interface IProps {
  children?: ReactNode
}

const { useToken } = theme

const inputWithVerifyCodeStyle = {
  display: 'flex',
  alignItems: 'center'
}

const statisRenderMap = [
  { label: '浏览数', prop: 'browseNumber' },
  { label: '收藏数', prop: 'collectNumber' },
  { label: '评论数', prop: 'commentNumber' }
]

const operationRenderMap = [
  { label: '创建人', prop: 'createBy' },
  { label: '创建时间', prop: 'createTime' },
  { label: '更新人', prop: 'updateBy' },
  { label: '更新数据', prop: 'updateTime' }
]

const QuestionList: FC<IProps> = (props) => {
  const { token } = useToken()
  const navigate = useNavigate()

  const [newSearchConfig, setNewSearchConfig] = useState(
    getQuestionListSearch()
  )
  // 引入搜索、内容、弹框相关的hook
  const { pageContentRef, searchClick, resetClick } = usePageSearch()
  const { pageModalRef, onModalOk, onModalCancel, getCodeClick } = usePageModal(
    { okCb, cancelCb, afterCloseResetStatusCb }
  )
  const {
    store: { propIds },
    modal: [curModalConfig, setCurModalConfig],
    record: [currentRecord, setCurrentRecord],
    dispatch,
    toSecondAuth,
    handleJudgeChecked,
    handleSecondAuth
  } = usePageContent({ pageModalRef })

  // modal的确定按钮
  function afterCloseResetStatusCb() {
    // ！！！这一步非常关键，我们希望每次点击确认后要销毁这个modal框的状态，
    // 但是只有modal的配置发生改变才会重新渲染这个modal组件
    // 假如我们两次点击二次认证框，但是我们希望下一次进去消除上一次残留的状态，就要让他的配置发生改变，所以这里改为空
    // setCurModalConfig({})
    setCurModalConfig({})
  }

  function cancelCb() {
    setCurModalConfig({})
  }

  async function okCb(form: FormInstance | undefined) {
    // 获取当前配置的信息，看一下是属于什么类型的表单描述
    const { desc } = curModalConfig.formProps
    // 获取表单数据
    const values = form?.getFieldsValue()
    if (desc === ActionDesc.SecondAuth) {
      /** 二次认证 **/
      return toSecondAuth(values)
    }
  }

  // 通用：按钮的操作---这里能进行任意按钮的操作
  async function actionClick(key: any, record?: any) {
    setCurrentRecord(record)
    // 操作类型
    if (key === ActionDesc.Delete) {
      // 单删除
      handleSecondAuth(() => {
        confirmModal('是否删除该数据?').then(() =>
          dispatch(fetchPageDeleteAction(record.questionId))
        )
      })
    } else if (key === ActionDesc.BatchDelete) {
      // 批量删除
      handleJudgeChecked(() =>
        handleSecondAuth(() => {
          confirmModal('是否删除选中的数据?').then(() =>
            dispatch(fetchPageBatchDeleteAction(propIds))
          )
        })
      )
    } else if (key === ActionDesc.QuestionDetail) {
      // 查看详情
      setCurModalConfig(questionListModalDetail)
      pageModalRef.current?.openModal()
    } else if (key === ActionDesc.Edit) {
      // 修改题目 -->  跳转到题库创编页面
      navigate(RoutesPath.QuestionInfo, { state: { isEdit: true } })
    }
  }

  // 获取一二三级分类下拉框数据
  const fetchClassifyTypeQuestion = async () => {
    // 并行获取三个接口的数据
    const [{ data: data1 }, { data: data2 }, { data: data3 }] =
      await Promise.all([
        getClassifyTypeQuestion(0), // 一级分类接口请求
        getClassifyTypeQuestion(1), // 二级分类接口请求
        getClassifyTypeQuestion(2) // 三级分类接口请求
      ])
    // 将三个接口返回的数据封装成一个数组返回
    return [data1, data2, data3]
  }

  // 在组件挂载时获取分类数据并设置搜索配置
  useEffect(() => {
    // 定义异步函数获取分类数据并设置搜索配置
    const fetchAndSetSearchConfig = async () => {
      // 调用封装好的函数获取分类数据
      const res = await fetchClassifyTypeQuestion()
      // 根据分类数据生成新的搜索配置
      const newConfig = getQuestionListSearch(res)
      // 设置新的搜索配置
      setNewSearchConfig(newConfig)
    }
    // 调用异步函数获取分类数据并设置搜索配置
    fetchAndSetSearchConfig()
    // 将 fetchClassifyTypeQuestion 函数作为依赖传入 useEffect 中，以避免 ESLint 报错
  }, [])

  //定义一个自定义表格内容渲染的Map，包含多个渲染函数
  const customRenderMap: { [key in string]: any } = {
    // 分类类型的渲染函数
    cateType: (targetVal: any, record: any) => {
      const { classifyFirstName, classifySecondName, classifyThirdName } =
        record
      const types = [
        { label: '一级分类', value: classifyFirstName },
        { label: '二级分类', value: classifySecondName },
        { label: '三级分类', value: classifyThirdName }
      ]
      return types.map((item) => (
        <CateTypeWrapper colorPrimary={token.colorPrimary} key={item.value}>
          <Button size="small" type="link" className="label">
            {item.label}
          </Button>
          <Tag>{item.value}</Tag>
        </CateTypeWrapper>
      ))
    },
    // 题目类型的渲染函数
    questionType: (targetVal: string | number) => {
      const questionType =
        targetVal === 0 ? '单选题' : targetVal === 1 ? '多选题' : '判断题'
      const color =
        targetVal === 0 ? 'magenta' : targetVal === 1 ? 'gold' : 'blue'
      return <Tag color={color}>{questionType}</Tag>
    },
    // 编程语言类型标志的渲染函数
    codeFlag: (targetVal: any) => {
      return (
        <Tag color={targetVal === 1 ? 'success' : 'error'}>
          {targetVal === 1 ? '包含' : '不包含'}
        </Tag>
      )
    },
    // 题目的代码部分的渲染函数
    questionCode: (targetVal: any) => {
      const { algorithm } = localCache.getCache(CacheType.THEME_CONFIG)
      const isDark = algorithm === ThemeMode.Dark
      return (
        <ReactHighlightSyntax
          language={'JavaScript'}
          theme={isDark ? 'AtomOneDark' : 'AtomOneLight'}
        >
          {targetVal?.code}
        </ReactHighlightSyntax>
      )
    },
    // 题目选项的渲染函数
    questionOptions: (targetVal: any) => {
      return targetVal?.map((item: any) => (
        <p key={item.optionName}>
          {item.optionName}：{item.optionValue}
        </p>
      ))
    },
    // 题目答案的渲染函数
    questionAnswer: (targetVal: any) => {
      return targetVal?.map((item: any) => (
        <Tag key={item} color="geekblue">
          {item}
        </Tag>
      ))
    },
    // 默认的渲染函数
    default: (targetVal: any) => <span>{targetVal}</span>
  }

  // 定义一个渲染表格内容的函数，根据传入的参数选择相应的渲染函数
  function renderTableCpn(targetVal: any, record: any, customkey: string) {
    return customRenderMap[customkey ?? 'default'](targetVal, record)
  }

  return (
    <>
      <PageSearch
        config={newSearchConfig}
        searchClick={searchClick}
        resetClick={resetClick}
      ></PageSearch>
      <PageContent
        ref={pageContentRef}
        config={questionListContent}
        actionClick={actionClick}
      >
        {renderTableCpn}
      </PageContent>
      <PageModal
        ref={pageModalRef}
        modalConfig={curModalConfig}
        onOk={onModalOk}
        onCancel={onModalCancel}
      >
        {/*二级认证*/}
        <div key="code" style={inputWithVerifyCodeStyle}>
          <Input name="code" />
          <VerifyCodeButton onClick={getCodeClick} />
        </div>
        {/*查看详情*/}
        <DetailWrapper key="detail">
          <h4>题目解析：</h4>
          {currentRecord?.questionParse?.map((item: any) => {
            return (
              <Space.Compact key={item.optionName} style={{ width: '100%' }}>
                <Input
                  style={{ width: '5%' }}
                  disabled
                  defaultValue={item.optionName}
                />
                <Input
                  style={{ width: '90%' }}
                  disabled
                  defaultValue={item.optionValue}
                />
              </Space.Compact>
            )
          })}
          <h4>
            题目难度：
            <Rate
              style={{ fontSize: 13 }}
              disabled
              allowHalf
              defaultValue={currentRecord.questionScore}
            />
          </h4>
          <h4>
            题目标签：
            {currentRecord?.questionTag?.map((item: string) => {
              return (
                <Tag key={item} color="purple">
                  {item}
                </Tag>
              )
            })}
          </h4>
          <h4>数据统计</h4>
          <div className="stats-wrapper">
            {statisRenderMap.map((item) => {
              return (
                <span key={item.prop} className="item">
                  {item.label}：{' '}
                  <Tag color="warning">{currentRecord[item.prop]}</Tag>
                </span>
              )
            })}
          </div>
          <h4>操作信息</h4>
          <div className="operation-wrapper">
            {operationRenderMap.map((item) => {
              return (
                <span key={item.prop} className="item">
                  {item.label}： <Tag>{currentRecord[item.prop]}</Tag>
                </span>
              )
            })}
          </div>
        </DetailWrapper>
      </PageModal>
    </>
  )
}

export default memo(QuestionList)
